package org.scrumfx.dal;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.scrumfx.bean.User;
import org.scrumfx.util.HibernateUtil;

public class UserDAL
{
  public User getUser(int userId)
  {
    User user = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transaction = null;
    try
    {
      transaction = session.beginTransaction();
      user = (User) session.load(User.class, userId);
    }
    catch (HibernateException he)
    {
      if (transaction != null)
      {
        transaction.rollback();
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return user;
  }

  public User saveUser(User user)
  {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transaction = null;
    try
    {
      transaction = session.beginTransaction();
      session.saveOrUpdate(user);
      transaction.commit();
    }
    catch (HibernateException he)
    {
      if (transaction != null)
      {
        transaction.rollback();
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return user;
  }

  public void deleteUser(User user)
  {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transaction = null;
    try
    {
      transaction = session.beginTransaction();
      session.delete(user);
      transaction.commit();
    }
    catch (HibernateException he)
    {
      if (transaction != null)
      {
        transaction.rollback();
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  public int count()
  {
    int count = 0;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction transaction = null;
    try
    {
      transaction = session.beginTransaction();
      count = ((Long) session.createQuery("SELECT COUNT(*) FROM User")
          .uniqueResult()).intValue();
      transaction.commit();
    }
    catch (HibernateException he)
    {
      if (transaction != null)
      {
        transaction.rollback();
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return count;
  }
}
